package com.acme.emailing;

import com.acme.domain.client.Client;
import com.acme.domain.client.Gender;
import com.acme.exceptions.QueueException;

/**
 * Created by Student on 21.11.2014.
 */
public class EmailService {
    Queue queue = new Queue();
    private Thread thread;

    public EmailService() {
        this.thread = new Thread() {
            @Override
            public void run() {
                while (!isInterrupted()){
                    EmailService.this.sendQueued();
                }
            }
        };
    }

    void sendQueued() {
        while (true){
            //sending somehow
            Email email = null;
            try {
                email = queue.getEmail();
            } catch (InterruptedException e) {
                return;
            }
            System.out.println(email);
        }
    }

    public void sendNotificationEmail(Email email){
        try {
            queue.add(email);
        } catch (QueueException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        thread.start();
    }

    public void stop(){
        queue.setBlocked(true);
        synchronized (queue) {
            try {
                queue.notify();
            } catch (Exception e) {
                System.out.printf("wuuuut");
            }
            thread.interrupt();
        }
    }

    public static void main(String... args) {
        EmailService es = new EmailService();
        es.sendNotificationEmail(new Email(new Client("Smith", Gender.FEMALE), "ekr@db.com", "Dear Santa..."));
        try {
            System.out.println("main thread sleeping for 2sec");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("AWAke!");
        }
        es.stop();
    }
}
